<template>
  <Layout>
    <div class="user-container">
      <!-- 顶部操作区 -->
      <div class="action-bar">
        <el-button type="primary" @click="handleCreateUser">
          新建账号
        </el-button>
      </div>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="search-item">
              <span class="label">账号所属人</span>
              <el-input v-model="queryParams.ownerName" placeholder="请输入姓名或手机" clearable />
            </div>
          </el-col>
          <el-col :span="5">
            <div class="search-item">
              <span class="label">角色</span>
              <el-select v-model="queryParams.role" placeholder="全部" clearable style="width: 100%">
                <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="5">
            <div class="search-item">
              <span class="label">状态</span>
              <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 100%">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="8" style="text-align: right">
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 用户列表 -->
      <el-card class="table-card">
        <el-table
          v-loading="loading"
          :data="userList"
          style="width: 100%"
          border
        >
          <el-table-column prop="username" label="所属人姓名" min-width="120" />
          <el-table-column prop="mobilePhoneNumber" label="手机" min-width="120" />
          <el-table-column prop="roleName" label="角色" min-width="150" />
          <el-table-column prop="addedBy" label="添加人" min-width="100" />
          <el-table-column prop="createdAt" label="创建时间" min-width="160">
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status ? 'success' : 'danger'">
                {{ scope.row.status ? '启用' : '已停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="handleEditUser(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                :type="scope.row.status ? 'danger' : 'success'"
                link
                @click="handleStatusChange(scope.row)"
              >
                {{ scope.row.status ? '禁用' : '启用' }}
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleDeleteUser(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUserList, updateUserStatus, deleteUser } from '../../../api/user';
import { getRoleList } from '../../../api/role';
import Layout from '../../../components/Layout.vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// 角色选项
const roleOptions = ref<any[]>([]);

// 状态选项
const statusOptions = [
  { value: true, label: '启用' },
  { value: false, label: '已停用' }
];

// 查询参数
const queryParams = reactive({
  ownerName: '',
  role: '',
  status: ''
});

// 列表数据
const loading = ref(false);
const userList = ref<any[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const res: any = await getRoleList();
    roleOptions.value = res.results.map((item: any) => ({
      value: item.objectId,
      label: item.name
    }));
  } catch (error) {
    console.error('获取角色列表失败:', error);
  }
};

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params: any = {
      limit: pageSize.value,
      skip: (currentPage.value - 1) * pageSize.value,
      count: 1
    };

    // 添加过滤条件
    if (queryParams.ownerName) {
      params.where = {
        $or: [
          { username: { $regex: queryParams.ownerName } },
          { mobilePhoneNumber: { $regex: queryParams.ownerName } }
        ]
      };
    }

    if (queryParams.role) {
      params.where = params.where || {};
      params.where.roleName = queryParams.role;
    }

    if (queryParams.status !== '') {
      params.where = params.where || {};
      params.where.status = queryParams.status;
    }
    
    const res: any = await getUserList(params);
    userList.value = res.results.map((item: any) => ({
      ...item,
      status: item.status !== false // 默认为true
    }));
    total.value = res.count;
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchUserList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchUserList();
};

// 搜索
const handleQuery = () => {
  currentPage.value = 1;
  fetchUserList();
};

// 重置搜索
const resetQuery = () => {
  Object.keys(queryParams).forEach(key => {
    queryParams[key as keyof typeof queryParams] = '';
  });
  currentPage.value = 1;
  fetchUserList();
};

// 新建用户
const handleCreateUser = () => {
  router.push('/system/user/create');
};

// 编辑用户
const handleEditUser = (row: any) => {
  router.push(`/system/user/edit/${row.objectId}`);
};

// 启用/禁用用户
const handleStatusChange = (row: any) => {
  const statusText = row.status ? '禁用' : '启用';
  const newStatus = !row.status;
  
  ElMessageBox.confirm(
    `确定要${statusText}该用户吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateUserStatus(row.objectId, newStatus);
      ElMessage.success(`${statusText}成功`);
      row.status = newStatus;
    } catch (error) {
      console.error(`${statusText}失败:`, error);
      ElMessage.error(`${statusText}失败`);
    }
  }).catch(() => {
    // 取消操作
  });
};

// 删除用户
const handleDeleteUser = (row: any) => {
  ElMessageBox.confirm(
    '确定要删除该用户吗？删除后不可恢复！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteUser(row.objectId);
      ElMessage.success('删除成功');
      fetchUserList();
    } catch (error) {
      console.error('删除用户失败:', error);
      ElMessage.error('删除用户失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

// 页面加载时获取数据
onMounted(() => {
  fetchRoleList();
  fetchUserList();
});
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
}

.search-bar {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.search-item {
  display: flex;
  align-items: center;
}

.search-item .label {
  width: 80px;
  color: #606266;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 